import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes } from '@/types/data'
import { profile } from '@/types/user'
import { getProfile, removeProfile, setProfile } from '@/utils/storage'
import useStore from '..'

export default defineStore('user', {
  state() {
    return {
      profile: getProfile() as profile
    }
  },
  actions: {
    async login(data: { account: string, password: string }) {
      const res = await request.post<ApiRes<profile>>('/login', data)
      // console.log(res)
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    async sendSms(mobile: string) {
      await request.get('/login/code', {
        params: {
          mobile
        }
      })
    },
    async mobileLogin(data: {mobile: string, code: string}) {
      const res = await request.post<ApiRes<profile>>('/login/code', data)
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    logout() {
      removeProfile()
      this.profile = {} as profile
      const { cart } = useStore()
      cart.clearCart()
    },
    async qqLogin(data: { unionId: string, source: number }) {
      const res = await request.post<ApiRes<profile>>('/login/social', data)
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    async sendQQBindMsg(mobile: string) {
      await request.get<ApiRes<profile>>('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    async qqBindLogin(data: {unionId: string, mobile: string, code: string}) {
      const res = await request.post<ApiRes<profile>>('/login/social/bind', data)
      this.profile = res.data.result
      setProfile(res.data.result)
    },
    async sendQQPathMsg(mobile: string) {
      await request.get<ApiRes<profile>>('/register/code', {
        params: {
          mobile
        }
      })
    },
    
    async qqPatchLogin(data: any) {
      const res = await request.post<ApiRes<profile>>(
        `/login/social/${data.openId}/complement`,
        data
      )
      this.profile = res.data.result
      setProfile(res.data.result)
    }
  }
})